package com.lcq.httplib.client.adapter;

import android.text.TextUtils;

import com.lcq.httplib.ErrorEnum;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class StringCallAdapter extends AbsCallAdapter<String> {
    private static final OkHttpClient okHttpClient;

    static {
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(9000, TimeUnit.MILLISECONDS)
                .writeTimeout(9000, TimeUnit.MILLISECONDS)
                .connectTimeout(9000, TimeUnit.MILLISECONDS)
                .build();
    }

    public StringCallAdapter(RequestParams<String> requestParams) {
        super(requestParams);
    }

    @Override
    protected Call createOkHttpCall() {
        Request.Builder builder = new Request.Builder()
                .url(requestParams.getUrl());

        RequestBody requestBody = requestParams.getRequestBody();
        if (requestBody != null) {
            builder.post(requestBody);
        }

        Map<String, String> headers = requestParams.getHeaders();
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) {
                    continue;
                }
                builder.addHeader(key, value);
            }
        }

        return okHttpClient.newCall(builder.build());
    }

    @Override
    public void handleSuccessBody(ResponseBody responseBody) {
        try {
            String text = responseBody.string();
            requestParams.getCallback().onSuccess(text);
        } catch (IOException e) {
            e.printStackTrace();
            callbackFail(ErrorEnum.IO_EXCEPTION);
        }
    }
}
